package com.yd.mq.parse.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.yd.mq.parse.model.AlarmRecord;
import com.yd.mq.parse.service.AlarmRecordService;
import com.yd.mq.parse.utils.FileReadingUtils;

/**
 * 
 * @ClassName ManualParseController
 * @author z
 * @date 2017年8月25日 下午2:03:06
 */
@RestController
@RequestMapping("/Manual")
public class ManualParseController {

	@Autowired
	private FileReadingUtils	fileReadingService;

	/* 日志处理 */
	private Logger				log				= Logger.getLogger(this.getClass().getName());
	private SimpleDateFormat	dateFormat		= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private ExecutorService		executorService	= Executors.newCachedThreadPool();

	@RequestMapping("test")
	@ResponseBody
	public String test() {
		log.info("执行任务!");
		// http://localhost:20001/Manual/test
		String msg = "Manual/Parse";
		return "测试:" + msg;
	}

	/* 数据入库服务 */
	@Resource
	private AlarmRecordService alarmRecordService;

	@RequestMapping("testDB")
	@ResponseBody
	public String testDB() {
		log.info("执行任务!");
		AlarmRecord alarmRecord = new AlarmRecord();

		alarmRecord.setcFp0("516884307");
		alarmRecord.setcFp1("4021743532");
		alarmRecord.setcFp2("190011648");
		alarmRecord.setcFp3("731022259");
		alarmRecord.setAlarmNo("7657");

		alarmRecord.setCancelReceivedTime(new Date());
		alarmRecord.setAlarmCancelTime(new Date());
		alarmRecord.setAlarmCancelSerial("2097902");

		AlarmRecord record = alarmRecordService.selectAlarmRecord(alarmRecord);

		String str = JSON.toJSONString(record);

		String msg = "Manual/Parse";
		return "测试:" + msg + str;
	}

	@RequestMapping("Parse")
	@ResponseBody
	public String parse(String start_time, String end_time) {
		StringBuffer sb = new StringBuffer();
		sb.append("开始执行任务 - ");
		log.info("执行任务!");
		// http://localhost:20001/Manual/Parse?start_time=2017-09-08
		// 09:12:00&end_time=2017-09-08 09:12:00
		sb.append("start_time:" + start_time + " - ");
		sb.append("end_time:" + end_time + " - ");
		try {
			sb.append("开始运行线程 - ");
			Date sdate = dateFormat.parse(start_time);
			Date edate = dateFormat.parse(end_time);
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					fileReadingService.readFilePath(sdate, edate);
				}
			});

		} catch (ParseException e) {
			e.printStackTrace();
			sb.append("出现异常:" + e.getMessage() + " - ");
		}

		sb.append("请等待线程执行结束");

		return sb.toString();
	}
}
